package com.cskaoyan.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import com.cskaoyan.bean.auth.WxLoginVo;
import com.cskaoyan.bean.common.BaseRespVo;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author stone
 * @date 2022/11/22 11:21
 */
@RestController
@RequestMapping("wx/auth")
public class WxAuthController {

    @Autowired
    private WxMaService wxMaService;

    Logger log = LoggerFactory.getLogger(WxAuthController.class);

    @RequestMapping("login_by_weixin")
    public BaseRespVo loginByWeixin(@RequestBody WxLoginVo wxLoginVo) {
        String code = wxLoginVo.getCode();
        if (StringUtils.isBlank(code)) {
            return BaseRespVo.invalidData("empty jscode");
        }

        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
            log.info(session.getSessionKey());
            log.info(session.getOpenid());
            //TODO 可以增加自己的逻辑，关联业务相关数据
            wxMaService.getUserService().getUserInfo()
            return BaseRespVo.ok(session.getOpenid());

        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
            return BaseRespVo.unAuthc();
        } finally {
            WxMaConfigHolder.remove();//清理ThreadLocal
        }

    }
}
